/**
 * MaintainabilityServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;



import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.Department;
import org.jackysoft.entity.Maintainability;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.MaintainabilityService;
import org.jackysoft.util.DateUtils;
import org.jackysoft.util.Page;
import org.joda.time.DateTime;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class MaintainabilityServiceImpl extends
AbstractStringIdServiceImpl<Maintainability> implements
		MaintainabilityService {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3947023657658751130L;
	final static Log logger = LogFactory
			.getLog(MaintainabilityServiceImpl.class);

	public MaintainabilityServiceImpl() {
		this.type = Maintainability.class;
	}

	@Override
	public Page statByDate(DateTime date) throws DataAccessException {
		String hql = String
				.format("select new org.jackysoft.service.impl.MaintainVo(count(m.id) as count,m.declarer as declarer) " +
						"from %s m where year(m.startDate)=%d and month(m.startDate)=%d " +
						"group by m.declarer.department " +
						"order by m.startDate desc ",
						table(), date.getYear(),date.getMonthOfYear());
        Page pageData = new Page();
        pageData.setPage(0);
        pageData.setOffset(20);
        List list = query(hql).list();
        pageData.setRows(list);
        return pageData;
	}

	@Override
	public Page statByOwner(Department owner,DateTime date,Integer page,Integer offset) throws DataAccessException {
		
		String hql = String.format("select count(*) from %s m where m.declarer.department.id='%s' and year(m.startDate)=%d and month(m.startDate)=%d ", 
				table()
				,owner.getId()
				, date.getYear()
        		, date.getMonthOfYear()
				);
	    
		Page pageData = new Page();
		pageData.setPage(page);
		pageData.setOffset(offset);
		Object obj = this.query(hql).uniqueResult();
		pageData.setRecords(Integer.parseInt(obj.toString()));		
		hql = String.format("from %s m where m.declarer.department.id='%s' and year(m.startDate)=%d and month(m.startDate)=%d ", 
				table()
				,owner.getId()
				, date.getYear()
        		, date.getMonthOfYear()
				);
		List itr = query(hql).setFirstResult(pageData.getFrom()).setMaxResults(offset).list();
		pageData.setRows(itr);
		return pageData;
	}

}